package com.pi.shisan.service.schedule;

import com.pi.shisan.service.schedule.job.SecondNotifyJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @author Shisan
 * @version V1.0.0
 * @Package com.shisan.pi.clock
 * @ClassName: Test
 * @Description:
 * @date 2019年12月20日 14:43
 */
public class ScheduleCreater {

    private final static String JOB_NAME = "CLOCK_JOB_%d";

    private final static String TRIGGER_NAME = "CLOCK_TRIGGER_%d";

    private final static String GROUP_NAME = "CLOCK_GROUP";

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private SecondNotifyJob secondNotifyJob;

    private Scheduler scheduler;

    public Scheduler createAndStartDefault() throws Exception{
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobDetail jobDetail = JobBuilder.newJob(SecondNotifyJob.class)
            .withIdentity(String.format(JOB_NAME,0), GROUP_NAME)
            .build();
        CronTrigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity(String.format(TRIGGER_NAME,0), GROUP_NAME)
            .forJob(jobDetail)
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ? "))
            .build();
        scheduler.scheduleJob(jobDetail,trigger);
//        SpringBeanJobFactory springBeanJobFactory = new SpringBeanJobFactory();
//        springBeanJobFactory.setApplicationContext(AppUtil.getApplicationContext());
        //这样写会导致所有的job都变成这个job，但目前项目里仅一个所以暂时这么偷工减料了
        scheduler.setJobFactory((t,s)->secondNotifyJob);
        this.scheduler = scheduler;
        return scheduler;
    }

    public Scheduler getScheduler() {
        return scheduler;
    }
}
